"use strict"
const sendStat = require("../extend/helper").sendStat
// 游戏相关逻辑
// 获取玩家数据// 检测是否开放模块
module.exports = () => {
	/** @param {import("egg").Context} ctx 	 */
	async function game(ctx, next) {
		let oid = ctx.userInfo.oid

		let config = ctx.app.config
		let moduleApplicat = await ctx.app.cache.moduleApplicat
		let localModule = moduleApplicat.find((v) => {
			return v.stat && v.mid == config.empire.moduleId &&
				v.aid == ctx.userInfo.aid
		})
		if (!localModule) {
			ctx.status = 401
			ctx.body = sendStat(config.constant.MODULE_OPEN, "敬请期待")
			return
		}
		let key = ctx.app.config.redisPrefix.gameUser + oid
		let gameUser = await ctx.service.empire.getGameUserCache(oid)
		if (!gameUser) {
			try {
				let res = await ctx.service.empire.findOrCreateUser(oid)
				gameUser = res[0]
			} catch (error) {
				ctx.body = sendStat(config.constant.ERROR_PERMISS_NOT_ALLOWED, {msg: "创建用户失败/未授权"})
				ctx.logger.error("创建用户失败")
				return
			}
		}
	
		ctx.gameUser = gameUser
		ctx.gameUser.ip =ctx.service.server.getCurrentIpInt()
		await next()
		await ctx.app.redis.set(key, JSON.stringify(gameUser), "ex", 3000) // 保存进内存
	}
	return game
}